﻿@page "/protocol"
@inherits SsoCompontentBase
@inject IWebHostEnvironment _environment
@layout SimpleLayout

<PModal Persistent
        Title="@T("RegistrationAgreement")"
        OnSave="ProtocolSaveAsync"
        ValueChanged="OnValueChangedAsync"
        SaveText="@T("Agree")"
        Value="Visible"
        MaxWidth="1000"
        Width="@("80%")">
    <div class="protocol" style="display: contents">
        <MMarkdownIt Source="@_source"
                     Html>
        </MMarkdownIt>
    </div>
</PModal>

@code
{
    [CascadingParameter(Name = "Culture")] private string? Culture { get; set; }

    [Parameter] public bool Visible { get; set; }

    [Parameter] public EventCallback<bool> VisibleChanged { get; set; }

    [Parameter] public EventCallback<bool> OnSuccess { get; set; }

    [Parameter] public EventCallback<bool> OnClose { get; set; }

    private string? _source;
    private string? _prevCulture;

    protected override async Task OnParametersSetAsync()
    {
        await base.OnParametersSetAsync();

        if (_prevCulture != Culture)
        {
            _prevCulture = Culture;
            await UpdateMdSourceAsync();
        }
    }

    private async Task UpdateMdSourceAsync()
    {
        _source = await File.ReadAllTextAsync(Path.Combine(System.IO.Directory.GetCurrentDirectory(), $"wwwroot/data/user-protocol.{Culture}.md"));
    }

    private async Task ProtocolSaveAsync()
    {
        if (OnSuccess.HasDelegate)
            await OnSuccess.InvokeAsync();
        Visible = false;
    }

    private async Task OnValueChangedAsync(bool value)
    {
        Visible = value;
        if (!value && OnClose.HasDelegate)
        {
            await OnClose.InvokeAsync();
        }
    }
}